import { isObject, def } from "../util/index.js";
import { arrayMethods } from "./array.js";
class Observer {
  constructor(value) {
    console.log("🚀 ~ Observer ~ constructor ~ value:", value);
    // vue如果数据的层次过多 需要递归的去解析对象中的属性，依次增加set和get方法
    def(value, "__ob__", this);
    if (Array.isArray(value)) {
      //对方法重写
      value.__proto__ = arrayMethods;
      this.observeArray(value);
    } else {
      this.walk(value);
    }
  }
  walk(data) {
    let keys = Object.keys(data);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const value = data[key];
      defineReactive(data, key, value); //定义相应式数据
    }
  }
  observeArray(value) {
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      observe(item);
    }
  }
}

function defineReactive(data, key, value) {
  observe(value);
  Object.defineProperty(data, key, {
    get() {
      console.log(`${key}属性被读取了`);
      return value;
    },
    set(newValue) {
      if (newValue === value) return;
      console.log(`${key}属性被修改了`);
      observe(newValue);
      value = newValue;
    },
  });
}

export function observe(data) {
  //   console.log("🚀 ~ observe ~ data:", data);
  const isObj = isObject(data);
  if (!isObj) return;
  //   console.log("🚀 ~ observe ~ datadow:", data);
  new Observer(data);
}
